{% extends "pc/template.html" %}

{% block title %}
用户列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .container-xxl {
        padding: 2rem 1.5rem;
    }
    
    .card {
        margin: 1rem 0;
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        transition: all 0.3s ease;
    }
    
    .card:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    
    .card-header {
        background: #fff;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        border-radius: 1rem 1rem 0 0 !important;
    }
    
    .card-header h5 {
        color: #566a7f;
        font-weight: 600;
        margin: 0;
    }
    
    .btn-primary {
        background: #696cff;
        border-color: #696cff;
        padding: 0.5rem 1rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .btn-primary:hover {
        background: #5f61e6;
        border-color: #5f61e6;
        transform: translateY(-1px);
    }
    
    .table-responsive {
        margin: 0;
        padding: 1rem;
    }
    
    .table {
        margin: 0;
    }
    
    .table thead th {
        background: #f8f9fa;
        color: #566a7f;
        font-weight: 600;
        border-bottom: 2px solid #e9ecef;
        padding: 1rem;
    }
    
    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
        color: #697a8d;
        border-bottom: 1px solid #e9ecef;
    }
    
    .table tbody tr {
        transition: all 0.2s ease;
    }
    
    .table tbody tr:hover {
        background: #f8f9fa;
    }
    
    .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #fff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
    }
    
    .user-avatar:hover {
        transform: scale(1.1);
    }
    
    .action-buttons .btn {
        padding: 0.4rem 0.6rem;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-buttons .btn:hover {
        transform: translateY(-2px);
    }
    
    .btn-info {
        background: #03c3ec;
        border-color: #03c3ec;
        color: #fff;
    }
    
    .btn-info:hover {
        background: #02a8c8;
        border-color: #02a8c8;
        color: #fff;
    }
    
    .btn-warning {
        background: #ffab00;
        border-color: #ffab00;
        color: #fff;
    }
    
    .btn-warning:hover {
        background: #e69a00;
        border-color: #e69a00;
        color: #fff;
    }
    
    .btn-danger {
        background: #ff3e1d;
        border-color: #ff3e1d;
        color: #fff;
    }
    
    .btn-danger:hover {
        background: #e63617;
        border-color: #e63617;
        color: #fff;
    }
    
    /* 骨架屏样式 */
    .avatar-skeleton {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
    }
    
    @keyframes skeleton-loading {
        0% {
            background-position: 200% 0;
        }
        100% {
            background-position: -200% 0;
        }
    }
    
    /* 分页样式 */
    .pagination {
        margin: 1rem 0 0 0;
        justify-content: center;
    }
    
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        color: #566a7f;
        background-color: #fff;
        border: 1px solid #d9dee3;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
        color: #fff;
    }
    
    .pagination .page-link:hover {
        color: #696cff;
        background-color: #f5f5f9;
        border-color: #d9dee3;
        transform: translateY(-1px);
    }
    
    .pagination .page-item.disabled .page-link {
        color: #a3a4cc;
        pointer-events: none;
        background-color: #fff;
        border-color: #d9dee3;
    }
    
    /* 模态框样式 */
    .modal-content {
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    
    .modal-header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
    }
    
    .modal-title {
        color: #566a7f;
        font-weight: 600;
    }
    
    .modal-body {
        padding: 1.5rem;
    }
    
    .modal-footer {
        border-top: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
    }
    
    .form-label {
        color: #566a7f;
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control {
        border-radius: 0.5rem;
        border: 1px solid #d9dee3;
        padding: 0.5rem 1rem;
        transition: all 0.2s ease;
    }
    
    .form-control:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.2rem rgba(105, 108, 255, 0.25);
    }
    
    .form-check {
        margin-bottom: 0.5rem;
    }
    
    .form-check-input {
        border-radius: 0.25rem;
    }
    
    .form-check-input:checked {
        background-color: #696cff;
        border-color: #696cff;
    }
    
    .form-check-label {
        color: #697a8d;
    }
    
    /* 动画效果 */
    .fade-enter-active, .fade-leave-active {
        transition: opacity 0.3s ease;
    }
    
    .fade-enter-from, .fade-leave-to {
        opacity: 0;
    }
    
    /* 响应式调整 */
    @media (max-width: 768px) {
        .container-xxl {
            padding: 1rem;
        }
        
        .card-header {
            padding: 1rem;
        }
        
        .table-responsive {
            padding: 0.5rem;
        }
        
        .action-buttons .btn {
            padding: 0.3rem 0.5rem;
            margin: 0 0.1rem;
        }
    }
    
    /* 下拉菜单样式 */
    .dropdown-menu {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        padding: 0.5rem;
        min-width: 160px;
    }
    
    .dropdown-item {
        padding: 0.6rem 1rem;
        color: #697a8d;
        border-radius: 0.4rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .dropdown-item:hover {
        background: #f8f9fa;
        color: #566a7f;
    }
    
    .dropdown-item i {
        font-size: 1.1rem;
    }
    
    .dropdown-item.view {
        color: #03c3ec;
    }
    
    .dropdown-item.edit {
        color: #ffab00;
    }
    
    .dropdown-item.delete {
        color: #ff3e1d;
    }
    
    .dropdown-item.view:hover {
        background: rgba(3, 195, 236, 0.1);
    }
    
    .dropdown-item.edit:hover {
        background: rgba(255, 171, 0, 0.1);
    }
    
    .dropdown-item.delete:hover {
        background: rgba(255, 62, 29, 0.1);
    }
    
    .dropdown-toggle::after {
        display: none;
    }
    
    .action-btn {
        background: #f8f9fa;
        border: 1px solid #d9dee3;
        color: #697a8d;
        padding: 0.4rem 0.8rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-btn:hover {
        background: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
    }
    
    .action-btn i {
        font-size: 1.1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 用户列表卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">用户列表</h5>
            <button type="button" class="btn btn-primary" onclick="showAddUserModal()">
                <i class="bx bx-plus"></i> 添加用户
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>头像</th>
                            <th>用户名</th>
                            <th>邮箱</th>
                            <th>创建时间</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="mb-3">
                            <label class="form-label" for="username">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="password">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="email">邮箱</label>
                            <input type="email" class="form-control" id="email" name="email">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="avatar">头像</label>
                            <input type="file" class="form-control" id="avatar" name="avatar" accept="image/*">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addUser()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看用户详情模态框 -->
    <div class="modal fade" id="viewUserModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">用户详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-4">
                        <img id="userDetailAvatar" src="" alt="用户头像" class="rounded-circle" style="width: 100px; height: 100px; object-fit: cover;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <p id="userDetailUsername" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <p id="userDetailEmail" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">创建时间</label>
                        <p id="userDetailCreateTime" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">更新时间</label>
                        <p id="userDetailUpdateTime" class="form-control-static"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" id="editUserId">
                        <div class="mb-3">
                            <label class="form-label" for="editUsername">用户名</label>
                            <input type="text" class="form-control" id="editUsername" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editEmail">邮箱</label>
                            <input type="email" class="form-control" id="editEmail" name="email">
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editAvatar">头像</label>
                            <input type="file" class="form-control" id="editAvatar" name="avatar" accept="image/*">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">权限</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="is_superuser" id="editSuperuser1" value="1">
                                <label class="form-check-label" for="editSuperuser1">
                                    老板
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="is_superuser" id="editSuperuser2" value="2">
                                <label class="form-check-label" for="editSuperuser2">
                                    店长
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="is_superuser" id="editSuperuser3" value="3">
                                <label class="form-check-label" for="editSuperuser3">
                                    员工
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateUser()">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 全局变量
    let allUsers = []; // 存储所有用户数据
    let currentPage = 1; // 当前页码
    const itemsPerPage = 10; // 每页显示的数量

    // 页面加载完成后获取用户列表
    document.addEventListener('DOMContentLoaded', function() {
        getUserList();
    });

    // 获取用户列表
    function getUserList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get('/api/users/get_user_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allUsers = response.data.data;
                    currentPage = 1; // 重置到第一页
                    renderUserTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取用户列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 渲染用户表格
    function renderUserTable() {
        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageUsers = allUsers.slice(startIndex, endIndex);

        currentPageUsers.forEach(user => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${user.id}</td>
                <td>
                    ${user.avatar ? 
                        `<img src="${user.avatar}" class="user-avatar" alt="用户头像">` : 
                        `<div class="avatar-skeleton"></div>`
                    }
                </td>
                <td>${user.username}</td>
                <td>${user.email || '-'}</td>
                <td>${user.create_time}</td>
                <td>${user.update_time}</td>
                <td class="action-buttons">
                    <div class="dropdown">
                        <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-dots-vertical-rounded"></i>
                            <span>操作</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item view" href="#" onclick="viewUser(${user.id})">
                                    <i class="bx bx-show"></i>
                                    <span>查看</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item edit" href="#" onclick="editUser(${user.id})">
                                    <i class="bx bx-edit"></i>
                                    <span>编辑</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item delete" href="#" onclick="deleteUser(${user.id})">
                                    <i class="bx bx-trash"></i>
                                    <span>删除</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(allUsers.length / itemsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > Math.ceil(allUsers.length / itemsPerPage)) {
            return;
        }
        currentPage = page;
        renderUserTable();
        renderPagination();
    }

    // 显示添加用户模态框
    function showAddUserModal() {
        const modal = new bootstrap.Modal(document.getElementById('addUserModal'));
        document.getElementById('addUserForm').reset();
        modal.show();
    }

    // 添加用户
    function addUser() {
        const form = document.getElementById('addUserForm');
        const formData = new FormData(form);

        // 立即关闭添加用户模态框
        const addUserModal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
        addUserModal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.post('/api/users/register/', formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '用户添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getUserList();
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '添加用户失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 查看用户详情
    function viewUser(userId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/users/get_user/${userId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const user = response.data.data;
                    const avatarElement = document.getElementById('userDetailAvatar');
                    if (user.avatar) {
                        avatarElement.src = user.avatar;
                        avatarElement.style.display = 'block';
                    } else {
                        avatarElement.style.display = 'none';
                        avatarElement.parentElement.innerHTML = '<div class="avatar-skeleton" style="width: 100px; height: 100px; margin: 0 auto;"></div>';
                    }
                    document.getElementById('userDetailUsername').textContent = user.username;
                    document.getElementById('userDetailEmail').textContent = user.email || '-';
                    document.getElementById('userDetailCreateTime').textContent = user.create_time;
                    document.getElementById('userDetailUpdateTime').textContent = user.update_time;

                    const modal = new bootstrap.Modal(document.getElementById('viewUserModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取用户详情失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 删除用户
    function deleteUser(userId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这个用户吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/users/delete_user/${userId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '用户删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getUserList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除用户失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }

    // 编辑用户
    function editUser(userId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/users/get_user/${userId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const user = response.data.data;
                    document.getElementById('editUserId').value = user.id;
                    document.getElementById('editUsername').value = user.username;
                    document.getElementById('editEmail').value = user.email || '';
                    
                    // 处理权限选择
                    const superuserValue = user.is_superuser;
                    // 如果权限值不在 1-3 范围内，默认设置为员工
                    const validSuperuserValue = superuserValue >= 1 && superuserValue <= 3 ? superuserValue : 3;
                    document.querySelector(`input[name="is_superuser"][value="${validSuperuserValue}"]`).checked = true;

                    const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                console.error('获取用户信息错误：', error);
                Swal.fire('错误', '获取用户信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 更新用户
    function updateUser() {
        const form = document.getElementById('editUserForm');
        const formData = new FormData(form);
        const userId = document.getElementById('editUserId').value;

        // 获取选中的权限值
        const isSuperuser = document.querySelector('input[name="is_superuser"]:checked').value;
        formData.set('is_superuser', isSuperuser);

        // 立即关闭编辑用户模态框
        const editUserModal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
        editUserModal.hide();

        const loadingToast = Swal.fire({
            title: '保存中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.post(`/api/users/update_user/${userId}/`, formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '用户信息更新成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getUserList();
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                console.error('更新用户信息错误：', error);
                Swal.fire('错误', '更新用户信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}